#!/usr/bin/env python
#coding=utf-8
import time
import pandas as pd
from datetime import datetime as dt
from pandas import Series
from flask import Blueprint, g, request, redirect, url_for, render_template, make_response, session, current_app
from codingabc.helpers import log_debug, log_info, toint
from app.services.my_redis import Redis
from app.services.account import AccountService
from app.services.huobi_http import HuobiHttp
from app.services.okex_http import OkexHttp
from app.services.binance_http import BinaHttp

account = Blueprint('account', __name__)
_as = AccountService()

@account.route('/okex')
@account.route('/okex/<int:page>')
@account.route('/okex/<int:page>-<int:page_size>')
def okex(page=1, page_size=20):
    """okex帐户列表"""
    #logging.basicConfig(stream=sys.stdout, level=logging.INFO, format='%(asctime)s [%(filename)s:%(lineno)d:%(funcName)s]%(levelname)s %(message)s')
    g.title = u'okex帐户列表'
    g.page_type = ''

    args = request.args
    df_list_export  = toint(args.get('df_list_export', '0'))
    df1_list_export = toint(args.get('df1_list_export', '0'))
    fmt             = lambda x: '%.9f'% float(x) if float(x) > 0 else 0
    if Redis.get_data('df_list'):
        df_list     = Redis.get_data('df_list')
        df1_list    = Redis.get_data('df1_list')
        sum_account = Redis.get_data('sum_account')
    else:
        apikey    = '172bd79d-60c9-450b-b3c9-c3d53ff28eca'
        apisecret = 'ED6761A4244EDEA9D4F85AD800E01680'
        url       = "https://www.okex.com/api/v1"
        try:
            http= OkexHttp(url, apikey, apisecret)
        except Exception as e:
            log_info('### error:%s'% e)

        #print(http.userinfo())

        #print (' 现货行情 ')
        #print (http.klines('1min', 'ltc_btc', 10))

        #print(http.http_post_request('order_info.do', api_key=http.getApiKey()))
        #print(http.http_post_request('order_info.do', api_key=http.getApiKey(), order_id=-1))

        #print(http.http_post_request('orders_info.do', api_key=http.getApiKey(),  type=0))
        #print(http.http_post_request('orders_info.do', api_key=http.getApiKey(),  type=1))

        #print (u' 现货订单信息查询 ')
        #print (http.orderinfo('btc_usdt'))

        #print (u' 现货批量订单信息查询 ')
        #print (http.ordersinfo('ltc_eth','6426168,34144382','0'))


        #sys.exit(-1)
        #print (' 用户现货账户信息 ')
        #aa=http.userinfo()['info']['funds']['freezed']['eth']
        #print(aa)
        funds = http.userinfo()['info']['funds']
        # try:
        #     funds = http.userinfo()['info']['funds']
        # except Exception as e:
        #     return redirect(url_for('account.okex'))

        aa=funds['freezed']
        bb=funds['borrow']
        cc=funds['free']

        asset=aa.keys()
        locked=[]
        borrow=[]
        free=[]
        qy=[]

        #print(aa,bb,cc)

        for x in aa.values():
            xx=float(x)
            locked.append(xx)
        for y in bb.values():
            yy=float(y)
            borrow.append(yy)
        for z in cc.values():
            zz=float(z)
            free.append(zz)

        # a = (page -1)*page_size;
        # b = ((page - 1)*page_size + page_size)if page > 1 else page_size
        # df_list = zip(asset[a:b], locked[a:b], borrow[a:b], free[a:b])
        df_list = zip(asset,
                      map(fmt, locked),
                      map(fmt, borrow),
                      map(fmt, free))

        df=pd.DataFrame()
        df['币种']=asset
        df['冻结']=locked
        df['借贷']=borrow
        df['可用']=free
        qy=[]

        df1=df[(df['可用']>0) | (df['借贷']>0) | (df['冻结']>0)]
        for x in list(df1['币种']):
            if x=='usdt':
                p=1
            else:
                p = http.ticker(x+'_usdt')
                p=float(p['ticker']['last'])
                time.sleep(0.5)
            qy.append(p)
        df1['price']=qy
        df1['折合usdt']=df1['price']*df1['可用']

        freezed_and_free = df1['可用'] + df1['冻结']
        df1_list = zip(df1['币种'].tolist(),
                        map(fmt, freezed_and_free.tolist()),
                        map(fmt, df1['price'].tolist()),
                        map(fmt, df1['折合usdt'].tolist()))
        sum_account = reduce(lambda x,y:x+y, df1['折合usdt'].tolist())

    Redis.set_data('df_list',df_list, ex=60)
    Redis.set_data('df1_list',df1_list, ex=60)
    Redis.set_data('sum_account',sum_account, ex=60)
    if df_list_export == 1:
        return _as.df_list_export(df_list)

    if df1_list_export == 1:
        return _as.df1_list_export(df1_list, sum_account)

    return render_template('account/okk.html.j2', **locals())


@account.route('/hb')
@account.route('/hb/<int:page>')
@account.route('/hb/<int:page>-<int:page_size>')
def hb(page=1, page_size=20):
    """火币帐户列表"""
    g.title = u'火币帐户列表'
    g.page_type = ''

    args = request.args
    a_list_export = toint(args.get('a_list_export', '0'))

    if Redis.get_data('a_list'):
        a_list     = Redis.get_data('a_list')
    else:
        url = "https://api.huobipro.com"
        #dreamy
        #apiKey = "3af5ee91-4bc1407b-d68cd6a5-7291b"
        #apiSecret    = "319c3ea1-88eeb820-a80d5ae8-3f93b"

        #simons
        apiKey = "8d22783f-7cb9e4c6-40ccd735-fa087"
        apiSecret = "76b99517-fa66c3f7-eb9282d8-01c48"
        http = HuobiHttp(url, apiKey, apiSecret)

        ddd=[]
        #ddd.columns=['a','b','c','d']

        ad=http.accounts()
        for x in ad['data']:
            data=http.balance(x['id'])['data']
            aa=data['list']
            ccy=[]
            tp=[]
            bl=[]
            zh=[]
            jys=[]

            for y in aa:
                if float(y['balance'])>0:
                    ccy.append(y['currency'])
                    tp.append(time.strftime('%Y-%m-%d %H:%M',time.localtime()))
                    bl.append('%.6f' % float(y['balance']))
                    jys.append(u'火币')
                    if y['currency'] !='usdt':
                        tt=y['currency']+'usdt'
                        ww=http.detail_merged(tt)['tick']['ask'][0]
                        zh.append('%.6f' % float(float(y['balance'])*ww))
                    else:
                        zh.append('%.6f' % float(y['balance']))

            df=pd.DataFrame()

            df['币种']=ccy
            df['交易所']=jys
            df['导出时间']=tp
            df['持仓数量']=bl
            df['折合usdt']=zh
            if df.empty:
                pass
            else:
                ddd.append(df)

        a=ddd[0]

        for i in range(len(ddd)-1):

            a=pd.concat([a,ddd[i+1]])

        a_list = zip(a['币种'].tolist(),
                     a['交易所'].tolist(),
                     a['导出时间'].tolist(),
                     a['持仓数量'].tolist(),
                     a['折合usdt'].tolist())

    Redis.set_data('a_list',a_list, ex=60)
    if a_list_export == 1:
        return _as.a_list_export(a_list)

    return render_template('account/hb.html.j2', a_list=a_list)


@account.route('/ba')
@account.route('/ba/<int:page>')
@account.route('/ba/<int:page>-<int:page_size>')
def ba(page=1, page_size=20):
    """币安账户列表"""

    args = request.args
    ba_list_export = toint(args.get('ba_list_export', '0'))

    url = "https://api.binance.com"
    apiKey   = "i5gVlrajCWSpQulsTbYZUC1Prp2TvxPxF16jjYnHSdo13LfFAi0fUEAjd0Vu7DME"
    apiSecret= "OYzRJA6B2gxAkETIg1eDGJWZsf1unz5Rrl1aVewelkB3iNLUsArYWedOtonBNeTe"

    http = BinaHttp(url, apiKey, apiSecret)
    data=http.account()['balances']

    lock, free, asset, lltime, qy, jys=[], [], [], [], [], []
    for x in data:
        locked=float(x['locked'])
        freed=float(x['free'])
        if locked>0 or freed>0:
            lock.append(locked)
            free.append(freed)
            jys.append(u'币安')
            asset.append(x['asset'])
            ttt=time.strftime('%Y-%m-%d %H:%M',time.localtime())
            lltime.append(ttt)
            print(lltime)

            if x['asset'] =='USDT':
                qy.append(freed+locked)
            else:
                a=(float(http.ticker(x['asset']+'USDT')['bidPrice']))
                qy.append((locked+freed)*a)

    df=pd.DataFrame()
    df['币种']=asset
    df['交易所']=jys
    df['导出时间']=lltime
    df['持仓数量']=pd.Series(free)+pd.Series(lock)
    df['折合usdt']=qy
    aa=str(dt.today()).split(' ')[0]
    df.to_csv('binance_%s.csv'%aa)
    log_info(df)

    if ba_list_export == 1:
        return _as.ba_list_export(ba_list_export)

    return render_template('account/ba.html.j2', ba_list_export=ba_list_export)

